<template>
    <a-modal
        :title="isEdit ? '编辑热榜' : '新增热榜'"
        v-model:open="visible"
        @ok="handleSubmit"
        @cancel="handleCancel"
        :confirm-loading="confirmLoading"
    >
        <a-form ref="formRef" :model="formModel" :rules="rules" layout="vertical">
            <a-form-item label="热榜内容" name="title">
                <a-textarea
                    v-model:value="formModel.title"
                    placeholder="请输入热榜内容"
                    :auto-size="{ minRows: 2, maxRows: 6 }"
                    allow-clear
                />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";

import type { HotlistEntity } from "@/api/globals";

const props = defineProps<{
    open: boolean;
    record?: HotlistEntity | null; // 编辑时传入，新增时为 null 或 undefined
}>();

const emit = defineEmits<{
    (e: "update:open", value: boolean): void;
    (e: "success"): void;
}>();

const visible = computed(() => props.open);

// 表单引用
const formRef = ref();

// 表单数据
const formModel = reactive({
    title: ""
});

// 是否为编辑模式
const isEdit = computed(() => !!props.record?.id);

// 确认加载状态
const confirmLoading = ref(false);

// 表单验证规则
const rules = {
    title: [{ required: true, message: "请输入热榜内容", whitespace: true }]
};

// 监听 open 变化，初始化表单
watch(
    () => props.open,
    isOpen => {
        if (isOpen && props.record) {
            // 编辑：回填数据
            formModel.title = props.record.title || "";
        } else if (isOpen) {
            // 新增：清空表单
            formModel.title = "";
            formRef.value?.resetFields();
        }
    },
    { immediate: true }
);

// 提交表单
const handleSubmit = async () => {
    try {
        const values = await formRef.value.validateFields();
        confirmLoading.value = true;

        if (isEdit.value) {
            // 调用编辑 API
            await Apis.HotlistAdmin.edit({
                pathParams: { id: props.record!.id },
                data: values
            });
        } else {
            // 调用新增 API
            await Apis.HotlistAdmin.create({ data: { ...values, hotScore: Math.floor(Math.random() * 10000) + 1 } });
        }

        emit("success"); // 通知父组件刷新
        handleCancel(); // 关闭弹窗
    } catch (error) {
        console.error("表单提交失败:", error);
    } finally {
        confirmLoading.value = false;
    }
};

// 取消/关闭
const handleCancel = () => {
    emit("update:open", false);
};

// defineExpose({
//     visible
// });
</script>
